package com.fly.demo.job;

import java.util.stream.IntStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * CleanDataJob
 * 
 * @author 00fly
 * @version [版本号, 2022年11月30日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Component
public class CleanDataJob
{
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    /**
     * 7-23点每1分钟执行
     * 
     */
    @Scheduled(cron = "0 0/1 7-23 * * ?")
    public void run()
    {
        // 保留最新100条日志，每次最多删除100条，最多执行100次
        IntStream.rangeClosed(1, 100)
            .map(n -> jdbcTemplate.update("DELETE FROM user WHERE id IN(SELECT id FROM user ORDER BY create_time DESC LIMIT 100, 100)"))
            .peek(count -> log.info("######## deleted: {}", count)) // debug
            .anyMatch(count -> count <= 0);
    }
}
